import axios from 'axios'
import {
  Toast
} from 'vant';
import {
  getToken
} from '@/utils/auth'
import {
  useCounterStore
} from '@/pinia/user.js'

// axios.defaults.withCredentials = true
// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_URL, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000 // request timeout
})

// const Router = 

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    const CounterStore = useCounterStore()
    if (CounterStore.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */
  response => {
    const res = response.data
    if (response.request.responseType === 'blob') {
      return response
    }
    // 下载文件
    if(!response.headers['content-type']){
      response.headers['content-type'] = "1111"
      Toast.fail('接口没有返回任何东西')
    }
    if (response.headers && (response.headers['content-type'].indexOf('application/vnd.ms-excel') > -1 ||
        response.headers['content-type'].indexOf('application/octet-stream') > -1)) {
      return response
    }
    // if the custom code is not 20000, it is judged as an error.
    if (res.success !== true) {
      // Message({
      //   message: res.message || 'Error',
      //   type: 'error',
      //   duration: 5 * 1000
      // })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        Toast.fail('请求错误请重试')
      }
      return res
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

export default service